/**
 * 
 */
$(document).ready(function() {
	$("form").submit(function() {
		return false;
	});
	var inObj_Query;
	var VAL = {
			//此处不同
			T_FBPBISSTO : "FBPBISSTK",
			NORMAL : "0000000",
			DISABLED_ATTR : {
				"disabled" : true
			},
			ENABLED_ATTR : {
				"disabled" : false
			}
		};
	
	var domObj ={
			$stockerDefConditionForm : $("#stockerDefConditionForm"),
			$stockerId : $("#stockerId"),
			$stockerDec : $("#stockerDec"),
			$stockerTyp : $("#stockerTyp"),
			$bayAreaSel : $("#bayAreaSel"),
			$totalCount : $("#totalCount"),
			$floorCoderSel : $("#floorCoderSel"),
			
			buttons : {
				$query_btn 	: $("#query_btn"),
			    $del_btn 	: $("#del_btn"),
			    $add_btn     : $("#add_btn"),
			    $update_btn  : $("#update_btn"),
			    $copy_btn    : $("#copy_btn"),
			    $save_btn : $("#save_btn"),
			    $rollback_btn : $("#rollback_btn"),
			    $clear_btn : $("#clear_btn"),
			},
				
			grids :{
				$stockerListGrd : $("#stockerListGrd"),
				$portListGrd : $("#portListGrd"),
				},
			
			dialogs :{
				//stoker查询模态框
				$queryStoDefDialog : $("#queryStoDefDialog"),
				$queryStoDefDialog_StokerIdTxt : $("#queryStoDefDialog_StokerIdTxt"),
				//stoker的按钮
				$queryStoDefDialog_cancelBtn : $("#queryStoDefDialog_cancelBtn"),
				$queryStoDefDialog_queryBtn : $("#queryStoDefDialog_queryBtn"),
				
				//Port添加或修改模态框
				$portDialog  : $("#portDialog"),
				$portId	: $("#portId"),
				$portUsage : $("#portUsage"),
				$transferId : $("#transferId"),
				//Port的按钮
				$portDialog_cancelBtn  : $("#portDialog_cancelBtn"),
				$portDialog_queryBtn : $("#portDialog_queryBtn"),
				
			}
		};

	

	//将值付给iary数组对象
	function comSetIary(iary, prop, val) {
		if (val) {
			iary[prop] = val;
		}
	}
	
	/*------------------------------------初始化Grid------------------------------------------*/
	//初始化stocker表格函数
	function  initStockerListGrd(){
		domObj.grids.$stockerListGrd.jqGrid({
            url : "",
			datatype : "local",
			mtype : "POST",
			height : 500,
			width : $("#stockerListDiv").width() * 0.99,
			autowidth : false,
			shrinkToFit : false,
			resizable : true,
			loadonce : true,
			viewrecords : true, 
			rownumbers : true,
			rowNum : 20, 
			emptyrecords : true,
            //multiselect : true, 多选
            colModel : [{name: 'stocker_id'      , index: 'stocker_id'       , label: 'Stocker ID',       width: 120},
    		            {name: 'stocker_dsc'     , index: 'stocker_dsc'     , label: 'Stocker 描述',     width: 200}
    		           ],

			pager : "stockerListPg",
			onSelectRow : function(rowId) {
				if (domObj.$stockerDec.attr("disabled") != "disabled") {
					showErrorDialog("", "目前处于编辑中，请勿进行查询操作");
					return false;
				}
				//先清空内容,再加载内容
				domObj.grids.$portListGrd.jqGrid("clearGridData");
		    	var inObj,outObj, stocker_id;
		    	var iary = {};
				//根据当前行的rowID获取当前行的数据
				var rowData = $("#stockerListGrd").jqGrid("getRowData",rowId);
				stocker_id = rowData.stocker_id;
				iary.stocker_id = stocker_id;
		    	inObj ={
		    			trx_id : VAL.T_FBPBISSTO,
						action_flg : 'I',
						iary : [iary]
		    	};
		    	outObj = comTrxSubSendPostJson(inObj);
		    	if (outObj.rtn_code === VAL.NORMAL) {
		    		//将右边信息栏制成不可变
		    		$("input").attr(VAL.DISABLED_ATTR);
		    		$("select").attr(VAL.DISABLED_ATTR);
		    		//修改按钮可用
		    		$("#update_btn").attr(VAL.ENABLED_ATTR);
					//设置port表格信息
					setGridInfo(outObj.oaryB, "#portListGrd", true);
					//设置stocker信息
					domObj.$stockerId.val(outObj.oary[0].stocker_id);
					domObj.$stockerDec.val(outObj.oary[0].stocker_dsc);
					domObj.$stockerTyp.val(outObj.oary[0].stocker_typ);
					SelectDom.setSelect(domObj.$bayAreaSel,outObj.oary[0].bay_id,outObj.oary[0].bay_id);
					domObj.$totalCount.val(outObj.oary[0].total_shelf_cnt);
					SelectDom.setSelect(domObj.$floorCoderSel,outObj.oary[0].floor_code,outObj.oary[0].floor_code);
				}
		    	
			}
		})
	};
	
	initStockerListGrd();
	
	//初始化Port jqGrid表格
	function initPortListGrid(){
		domObj.grids.$portListGrd.jqGrid({
			datatype : "local",//请求数据返回的类型。可选json,xml,txt
    		autoheight : true,
    		mtype : "POST",//向后台请求数据的ajax的类型。可选post,get
    		height : 400,
    		autowidth : true,//宽度根据父元素自适应
    		shrinkToFit : false,
    		scroll : true,
    		resizable : true,
    		rownumbers : true,
    		loadonce : true,
            viewrecords : true,
            //multiselect : true, 多选
            colModel : [{name: 'port_id'      , index: 'port_id'       , label: 'Port ID',       width: 220},
    		            {name: 'port_usage'     , index: 'port_usage'     , label: 'Port Usage',     width: 220},
            			{name: 'xfr_id'     , index: 'xfr_id'     , label: 'Transfer ID',     width: 220}
    		           ],

			pager : "portListPg"
		})
	};
	
	initPortListGrid();
	
	/*-------------------------------初始化选择框------------------------------------------*/
	var initSelectDom = {
		//1.初始化选择框：Floor Code
		initFloorCodeSel : function () {
			 addValueByDataCateFnc("#floorCoderSel","FBID","data_item",true);
		},
		/*//2.初始化选择框：Bay Area
		initBayAreaSel : function (){
			addValueByDataCateFnc("#bayAreaSel","AREA","data_ext",true);
		}*/
	};
	
	/*-------------------------------查询对话框函数-------------------------------------------*/
	 var queryDiaLog ={
		//1.stoker查询对话框	 
			 dialogStokerFnc : function (){
				var iary = {},outObj;
				comSetIary(iary, "stocker_id", $("#queryStoDefDialog_StokerIdTxt").val());
				inObj_Query = {
						trx_id : VAL.T_FBPBISSTO,
						action_flg : 'Q',
						iary : [iary],
						tbl_cnt : 1
					};
					outObj = comTrxSubSendPostJson(inObj_Query);
					if (outObj.rtn_code === VAL.NORMAL) {
						setGridInfo(outObj.oary, "#stockerListGrd", true);
						$('#queryStoDefDialog').modal("hide");
					}
					//右边信息表清空
					initFnc();
					domObj.grids.$portListGrd.jqGrid("clearGridData");
			 },
		//2.port新增或修改对话框
			 dialogPortFnc : function (){
				var  inObj, outObj, actionFlg,oaryB, tblCnt,newRowId,selRowId,rowData;
				actionFlg = domObj.dialogs.$portId.attr("disabled") === "disabled"
						? "U"
						: "A";
				var iaryB = {};
				var portId = domObj.dialogs.$portId.val().trim();
				var portUsage = domObj.dialogs.$portUsage.val().trim();
				var transferId = domObj.dialogs.$transferId.val().trim();
				if(portId ==""){
					showErrorDialog("", "PortId不能为空!");
					return false;
				}
				
				if(actionFlg =="A"){
					//得到表格中所有的portId，判重
					var rowDatas = domObj.grids.$portListGrd.getRowData();
					for(var i = 0 ;i < rowDatas.length; i++){
						if(portId == rowDatas[i].port_id){
							showErrorDialog("", "PortId已重复请重新输入！");
							return false;
						}
					}
					var newRowId = getGridNewRowID(domObj.grids.$portListGrd);
					domObj.grids.$portListGrd.addRowData(newRowId,{'port_id':portId,'port_usage':portUsage,'xfr_id':transferId});
					//默认选择新加的行    
					domObj.grids.$portListGrd.setSelection(newRowId, true); 
					$('#portDialog').modal("hide");
					showSuccessDialog("新增port信息成功,点击保存确认！");
				}else if (actionFlg =="U"){
					//更新修改行的数据
					selRowId = domObj.grids.$portListGrd.jqGrid("getGridParam","selrow");
					domObj.grids.$portListGrd.setRowData(selRowId,{'port_id':portId,'port_usage':portUsage,'xfr_id':transferId});
					$('#portDialog').modal("hide");
					showSuccessDialog("修改port信息成功,点击保存确认！");
				}
			 }
	 };
	 
	 //正则判断数字
	 function validate(){  
	       var reg = new RegExp("^[0-9]*$");  
	       var obj = document.getElementById("name");  
	    if(!reg.test(obj.value)){  
	        alert("请输入数字!");  
	    }
	 };
	
	/*----------------------------基础信息按钮函数---------------------------------------*/
	var buttonFnc1 = {
		queryFnc : function (){
			$('#queryStoDefDialog').modal({
				backdrop : true,
				keyboard : false,
				show : false
			});
			
			$('#queryStoDefDialog').unbind('shown.bs.modal');
			$("#queryStoDefDialog_queryBtn").unbind('click');
			$('#queryStoDefDialog').bind('shown.bs.modal');
			$('#queryStoDefDialog').modal("show");
			$("#update_btn").attr(VAL.ENABLED_ATTR);
			//模态框查询按钮绑定查询函数
			$("#queryStoDefDialog_queryBtn").bind('click', queryDiaLog.dialogStokerFnc);
			$("#queryStoDefDialog input").attr(VAL.ENABLED_ATTR);
			$('#queryStoDefDialog input').val("");
		},
		
		addFnc : function (){
			$("#stockerDefConditionForm select").attr(VAL.ENABLED_ATTR);
			$("#stockerDefConditionForm input").attr(VAL.ENABLED_ATTR);
			$("#stockerDefConditionForm select").empty();
			$("#stockerDefConditionForm input").empty();
			//修改按钮不可用
			$("#update_btn").attr(VAL.DISABLED_ATTR);
			//清空表格信息
			$("input").val("");
			$("select").empty();
			domObj.grids.$portListGrd.jqGrid("clearGridData");
			//initSelectDom.initBayAreaSel();
			initSelectDom.initFloorCodeSel();
		
		},
		
		updateFnc : function(){
			//先判断有没有选中行
			var selRowId = domObj.grids.$stockerListGrd.jqGrid("getGridParam","selrow");
			if (!selRowId) {
				showErrorDialog("", "请选择需要修改的Stocker信息");
				return false;
			}
			//主键不能修改
			$("#stockerDefConditionForm input").not($("#stockerId")).attr(VAL.ENABLED_ATTR);
			$("#stockerDefConditionForm select").attr(VAL.ENABLED_ATTR);
			//initSelectDom.initBayAreaSel();
			initSelectDom.initFloorCodeSel();
			
		},
		
		copyFnc : function(){
			var stockerid = domObj.grids.$stockerListGrd.jqGrid('getGridParam','selrow');
			if(stockerid==null){
				  showErrorDialog("", "请选择需要复制的stockerid信息！");
				  return false;
			}
			$("input").attr({'disabled':false});
		    $("select").attr({'disabled':false});
		    domObj.$stockerId.focus();
		    initSelectDom.initFloorCodeSel();
		},
		
		deleteFnc: function(){
			var selRowId, rowData, iary, inObj, outObj;
			//获得选中的行ID
			selRowId = domObj.grids.$stockerListGrd.jqGrid("getGridParam",
					"selrow");
			if (!selRowId) {
				showErrorDialog("", "请选择需要删除的Stocker信息");
				return false;
			}
			//删除按钮绑定删除事件
			$("#del_btn").showCallBackWarnningDialog({
				errMsg : "是否删除该Stocker信息,请确认!!!!",
				callbackFn : function(data) {
					if (data.result == true) {
						//获得选中行的数据
						rowData = domObj.grids.$stockerListGrd.jqGrid(
								"getRowData", selRowId);
						iary = {
							stocker_id: rowData.stocker_id,
						};
						inObj = {
							trx_id : VAL.T_FBPBISSTO,
							action_flg : "D",
							iary : [iary]
						};
						outObj = comTrxSubSendPostJson(inObj);
						if (outObj.rtn_code === VAL.NORMAL) {
							showSuccessDialog("删除Socker成功");
							domObj.grids.$stockerListGrd.jqGrid(
									"delRowData", selRowId);
							//删除完后页面除了Parameter信息，清空
							domObj.grids.$portListGrd.jqGrid("clearGridData");
							initFnc();
						}
					}
				}
			});
		},
		
		saveFnc : function(){
			var actionFlg, inObj, outObj, iary,iaryC ,iaryB,oary,newRowId,selRowId;
			if(domObj.$stockerId.attr("disabled") === "disabled"){
				actionFlg = "U";
			}else{
				actionFlg = "A";
			}
			var stockerId = domObj.$stockerId.val().trim();
			if(stockerId ==""){
				showErrorDialog("", "请先新增或修改!");
				return false;
			}
			
			var stockerDec = domObj.$stockerDec.val().trim();
			if (!stockerDec) {
				showErrorDialog("", "stocker描述不能为空");
				return false;
			}
			var stockerTyp = domObj.$stockerTyp.val().trim();
			if (!stockerTyp) {
				showErrorDialog("", "stocker类型不能为空");
				return false;
			}
			/*var bayAreaSel = domObj.$bayAreaSel.val().trim();
			if (!bayAreaSel) {
				showErrorDialog("", "Bay Area不能为空");
				return false;
			}*/
			var totalCount = domObj.$totalCount.val();
			if (!totalCount) {
				showErrorDialog("", "Total Count不能为空");
				return false;
			}
			var floorCoderSel =domObj.$floorCoderSel.val();
			if (!floorCoderSel) {
				showErrorDialog("", "楼层不能为空");
				return false;
			}
			
			var port = domObj.grids.$portListGrd.getRowData();
			var iaryB = [];
			for(var i = 0; i < port.length;i++){
				iaryB.push({
					stocker_id_fk : stockerId,
					port_id : port[i].port_id,
					port_usage : port[i].port_usage,
					xfr_id : port[i].xfr_id
				});
				};
				
			//保存的内容
			iary={
				stocker_id : stockerId,
				stocker_dsc : stockerDec,
				stocker_typ : stockerTyp,
				bay_id : "",
				total_shelf_cnt : totalCount,
				floor_code : floorCoderSel
			};

			//输给后台的数据
			inObj = {
					trx_id : VAL.T_FBPBISSTO,
					action_flg : actionFlg,
					iary : [iary],
					iaryB : iaryB,
				};
				outObj = comTrxSubSendPostJson(inObj);
				if (outObj.rtn_code === VAL.NORMAL) {
					$("input").attr(VAL.DISABLED_ATTR);
					$("select").attr(VAL.DISABLED_ATTR);
					if (actionFlg == "A") {
						var newRowId = getGridNewRowID("#stockerListGrd");
						domObj.grids.$stockerListGrd.jqGrid("addRowData", newRowId, iary);
						//默认选择新加的行
						domObj.grids.$stockerListGrd.setSelection(newRowId, true); 
						//保存成功后，修改按钮可用
						$("#update_btn").attr("disabled",false);
						showSuccessDialog("新增stocker信息成功");
					} else if (actionFlg == "U") {
						selRowId = domObj.grids.$stockerListGrd.jqGrid("getGridParam","selrow");
						domObj.grids.$stockerListGrd.jqGrid("setRowData",selRowId,outObj.oary[0]);
						showSuccessDialog("stocker信息更新成功");
					}
				}
				
		},
		
		//重回查询时的状态
		rollbackFnc : function(){
			if(domObj.$stockerDec.attr("disabled") == "disabled"){
				showErrorDialog("", "没有编辑，无需撤回");
				return false;
			}
		  $("#stockerDefConditionForm input").attr(VAL.DISABLED_ATTR);
		  $("#stockerDefConditionForm select").attr(VAL.DISABLED_ATTR);
		  var outObj = comTrxSubSendPostJson(inObj_Query);
		  if (outObj.rtn_code === VAL.NORMAL) {
			  setGridInfo(outObj.oary, "#stockerListGrd");
			  $("input").val("");
			  $("select").empty();
			  //修改按钮可用
			  $("#update_btn").attr(VAL.ENABLED_ATTR);
			  domObj.grids.$portListGrd.jqGrid("clearGridData");
			  domObj.grids.$zoneListGrd.jqGrid("clearGridData");
		  }
		},
		
		clearFnc : function(){
			initFnc();
			domObj.grids.$stockerListGrd.jqGrid("clearGridData");
			domObj.grids.$portListGrd.jqGrid("clearGridData");
			domObj.buttons.$update_btn.attr(VAL.ENABLED_ATTR);
		}
	};
	
	//按钮绑定对应函数
	$("#query_btn").bind('click',buttonFnc1.queryFnc);
	$("#add_btn").bind('click',buttonFnc1.addFnc);
	$("#update_btn").bind('click',buttonFnc1.updateFnc);
	$("#del_btn").bind('click',buttonFnc1.deleteFnc);
	$("#copy_btn").bind('click',buttonFnc1.copyFnc);
	$("#save_btn").bind('click',buttonFnc1.saveFnc);
	$("#rollback_btn").bind('click',buttonFnc1.rollbackFnc);
	$("#clear_btn").bind('click',buttonFnc1.clearFnc);
	
	/*--------------------------------Port信息和Zone按钮函数------------------------------*/
	var buttonFnc2 = {
		portAddFnc : function(){
			/*var stockerId =domObj.$stockerId.val().trim();
			if(stockerId == ""){
				showErrorDialog("", "请先确定stocker信息!");
				return false;
			};*/
			if(domObj.$stockerDec.attr("disabled") == "disabled"){
				showErrorDialog("", "目前不是编辑状态，不可新增Port信息。");
				return false;
			}
			
			$("#portDialog").modal({
				backdrop : true,
				keyboard : false,
				show : false
			});
			
			$("#portDialog").unbind('shown.bs.modal');
			$("#portDialog_queryBtn").unbind('click');
			$("#portDialog").bind('shown.bs.modal');
			$("#portDialog").modal("show");
			$("#portDialog input").attr(VAL.ENABLED_ATTR);
			$("#portDialog input").val("");
			$("#portDialog select").attr(VAL.ENABLED_ATTR);
			comAddValueByDataCateFnc("#portUsage","RTDM","data_ext","data_desc",true);
			//模态框查询按钮绑定查询函数
			$("#portDialog_queryBtn").bind('click', queryDiaLog.dialogPortFnc);
		},
		
		portUpdateFnc : function(){
			//判断有没有选中表格行
			var selRowId,rowData;
			selRowId = domObj.grids.$portListGrd.jqGrid("getGridParam","selrow");
			/*var stockerId = domObj.$stockerId.val().trim();
			if(stockerId == ""){
				showErrorDialog("", "请先确定stocker信息!");
				return false;
			};*/
			if(domObj.$stockerDec.attr("disabled") == "disabled"){
				showErrorDialog("", "目前不是编辑状态，不可更新Port信息。");
				return false;
			}
			
			if(selRowId == null){
			showErrorDialog("", "请先选择port信息!");
			return false;
			}
			$('#portDialog').modal({
				backdrop : true,
				keyboard : false,
				show : false
			});
			
			$("#portDialog").unbind('shown.bs.modal');
			$("#portDialog_queryBtn").unbind('click');
			$("#portDialog").bind('shown.bs.modal');
			$("#portDialog").modal("show");
			$("#portDialog input").attr(VAL.ENABLED_ATTR);
			$("#portId").attr(VAL.DISABLED_ATTR);
			$("#portDialog input").val("");
			//portId的值为选中表格的值
			rowData = domObj.grids.$portListGrd.jqGrid("getRowData",selRowId);
			$("#portId").val(rowData.port_id);
			SelectDom.setSelect($("#portUsage",rowData.port_usage));
			$("#transferId").val(rowData.xfr_id);
			//模态框查询按钮绑定查询函数
			$("#portDialog_queryBtn").bind('click', queryDiaLog.dialogPortFnc);
		},
		
		portDeleteFnc : function(){
			var selRowId,selRowId2,rowData,rowData2,inObj, outObj;
			var iaryB={};
			if(domObj.$stockerDec.attr("disabled") == "disabled"){
				showErrorDialog("", "目前不是编辑状态，不可删除Port信息。");
				return false;
			}
			//判断有没有选中pamListGrd表格行
			selRowId = domObj.grids.$portListGrd.jqGrid("getGridParam","selrow");
			if(selRowId == null){
				showErrorDialog("", "请先选择port信息!");
				return false;
			}
			
			//删除按钮绑定删除事件
			$("#delete_port_btn").showCallBackWarnningDialog({
				errMsg : "是否删除该Port信息,请确认!!!!",
				callbackFn : function(data) {
					if (data.result == true) {
						/*//获得选中行的数据
						selRowId2 = domObj.grids.$stockerListGrd.jqGrid("getGridParam","selrow");
						rowData = domObj.grids.$portListGrd.jqGrid("getRowData",selRowId);
						rowData2 =domObj.grids.$stockerListGrd.jqGrid("getRowData",selRowId2);
						comSetIary(iaryB, "stocker_id_fk", rowData2.stocker_id);
						comSetIary(iaryB, "port_id", rowData.port_id);
						inObj = {
							trx_id : VAL.T_FBPBISSTO,
							action_flg : "D",
							iaryB : [iaryB]
						};
						outObj = comTrxSubSendPostJson(inObj);
						if (outObj.rtn_code === VAL.NORMAL) {*/
							showSuccessDialog("删除该Port信息成功,点击保存确认删除！");
							domObj.grids.$portListGrd.jqGrid(
									"delRowData", selRowId);
						/*}*/
				}
				}
			});
		}
	};
	$("#add_port_btn").bind('click',buttonFnc2.portAddFnc);
	$("#update_port_btn").bind('click',buttonFnc2.portUpdateFnc);
	$("#delete_port_btn").bind('click',buttonFnc2.portDeleteFnc);
	
	/*--------------------------------页面初始化函数--------------------------------------------*/
		//页面输入初始化函数
		function initFnc() {
			$("input").attr(VAL.DISABLED_ATTR);
			SelectDom.initWithSpace($("select"));
			$("select").attr(VAL.DISABLED_ATTR);
			$("input").val("");
			//需要加验证的输入框初始化 不起作用
			/*domObj.$totalCount.addClass("intCss");
			domObj.dialogs.$zoneStdQ.addClass("intCss");*/
		}
		initFnc();


    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var domObjs = {
        W                   : $(window)       ,
        grids : {
            $leftDiv         : $(".leftDiv"),
            $rightDiv		: $(".rightDiv"),
            $stockerListDiv : $("#stockerListDiv"),
            $stockerListGrd : $("#stockerListGrd"),
            $tabPane2 : $("#tabPane2"),
			$portListDiv : $("#portListDiv"),
            $portListGrd : $("#portListGrd")
        }
    };


    //jqGrid表格自适应
    function resizeFnc(){
        var grdDivHeight,grdDivWidth;
        grdDivWidth = domObjs.W.width() - 120 - domObjs.grids.$rightDiv.width();
        grdDivHeight = domObjs.W.height() - domObjs.grids.$leftDiv.offset().top;

        domObjs.grids.$leftDiv.height(grdDivHeight);
        domObjs.grids.$stockerListDiv.width(grdDivWidth);
        domObjs.grids.$stockerListDiv.height(grdDivHeight*0.99 - 51);
        domObjs.grids.$stockerListGrd.setGridWidth(grdDivWidth*0.99);
        domObjs.grids.$stockerListGrd.setGridHeight(grdDivHeight*0.95 - 51 - 35);


        domObjs.grids.$portListDiv.width(domObjs.grids.$tabPane2.width() - 200);
        domObjs.grids.$portListDiv.height(grdDivHeight*0.99 - 51 - 95);
        domObjs.grids.$portListGrd.setGridWidth((domObjs.grids.$tabPane2.width() - 200)*0.99);
        domObjs.grids.$portListGrd.setGridHeight(grdDivHeight*0.95 - 51 - 35 - 95);
    };

    resizeFnc();
    domObjs.W.resize(function() {
        resizeFnc();
    });
	
})